package com.yh.csx.bsf.flow.engine;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.yh.csx.bsf.flow.provider.enums.TaskStateEnum;
import com.yh.csx.bsf.flow.core.db.DbHelper;
import com.yh.csx.bsf.flow.dao.dal.t_flow_dal;
import com.yh.csx.bsf.flow.dao.dal.t_task_dal;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import lombok.var;

import java.util.List;

/**
 * @author: chejiangyi
 * @version: 2019-11-06 10:07
 * 异常流程检测
 **/
@Slf4j
@JobHandler("errorFlowJob")
public class ErrorFlowJob extends IJobHandler {
    @Override
    public ReturnT<String> execute(String param) throws Exception {
        List<Integer> flowids = DbHelper.get(c-> new t_flow_dal().getNoTasksFlow(c));
        int trycount =2;
        for(int i=0;i<trycount;i++) {
            Thread.sleep(2 * 1000);
            for (val id : flowids.toArray(new Integer[flowids.size()])) {
                var count = DbHelper.get(c -> new t_task_dal().getCountOfTasks(c, id, TaskStateEnum.waiting.Value));
                if (count > 0) {
                    flowids.remove(id);
                }
            }
        }
        if(flowids!=null){
            flowids.forEach(o->{
                String msg = "尝试"+trycount+"次检测到流程没有待审批任务";
                DbHelper.call(c->{
                    new t_flow_dal().updateFlowError(c,o,msg);
                });
                log.error(msg+" flowid:"+o);
            });
        }
        return ReturnT.SUCCESS;
    }
}